Here's my JavaScript sample:
function createButtons(idDialog, tab, fn, param) {
var btns = new Array();
for (var i = 0; i < tab.length; i++) {
btns.push( {
text: (tab[i]>0 ? '+':'')+tab[i],
click: function(a) {
console.log(fn);
console.log(param);
fn(param);
$(this).dialog("close");
}
});
};
btns.push( {
text: "Close",
click: function() {
$(this).dialog("close");
}
});
$(idDialog).dialog('option', 'buttons', btns);
}
The params: fn is a function that should be called whenever we click the button, and param is a param that should be passed to the function.
When I use this code, console.log(fn) says undefined and console.log(param) says undefined. It kinddof doesn't recall the param.
How should I do?
I've asked JoshNaro to answer but he didn't so here's the solution he gave that works perfectly:
function createButtons(idDialog, tab, fn, param) {
var btns = new Array();
for (var i = 0; i < tab.length; i++) {
btns.push( {
text: (tab[i]>0 ? '+':'')+tab[i],
click: function(a) {
console.log(fn);
console.log(param);
fn(param);
$(this).dialog("close");
}
});
};
btns.push( {
text: "Close",
click: function() {
$(this).dialog("close");
}
});
$(idDialog).dialog('option', 'buttons', btns);
}
createButtons(
"#Hello",
['Save', 'Load'],
function(parameter) {
alert(parameter);
},
'World'
);
Related
i have the following reactjs code to generate two dropdown list where the ddlproducts gets loaded by ddlCategories selection. but when i called the function getDataById() and tried to print the ajax populated array data2 to alert(), there was no alert() there were two alerts none of the alerts were prompted. it shown this error message on the IE console,
execution did not reached the function getDataById() 'cus the alert() in that function even didn't execute
SCRIPT438: Object doesn't support property or method 'getDataById'
correction: once the calling of this.props.getDataById() was changed to this.getDataById() it worked
but how do populate the ddlProducts dropdown. how do i access tag of the ddlProducts and then add the options to it?
here is the code:
var gdata=[];
var trStyle = {
'color': 'black',
'border-style' :'solid',
'margin-left':'20%'
};
var HCOMP = React.createClass({
getInitialState:function(){
return{data1:[], data2:[], isMounted:false, selectedValue:0}
},
componentDidMount:function(){
this.getData();
this.setState({isMounted:true})
},
ddlProdCatsChanegeEvent: function(e) {
if (this.state.isMounted)
{
var newV = ReactDOM.findDOMNode(this.refs.refProdCats).value;
var seleValue = newV;
this.setState({selectedValue:newV}, function(){
this.getDataById(this.state.selectedValue);
alert(this.state.data2);
});
}
},
render: function() {
var prodCats = this.state.data1.map(function(ele, index){// <PRODCATSOPTION optValue={ele.ProductCategoryID} optText={ele.Name} />
return <option value={ele.ProductCategoryID} data-key={index}>{ele.Name}</option>
});
prodCats.unshift(<option value={''}>{'---- select category ------'}</option>)
return (<div>Prodcut Category:<br /><select id="ddlCategories" ref="refProdCats" onChange={this.ddlProdCatsChanegeEvent}>{prodCats}</select><br />
Products:<br /><select id="ddlPorducts" ref="refProds"></select><br /></div>
)
},
getDataById:function(catId){
var x = catId;
alert('rec id:'+x);
$.ajax({
url:'http://localhost:53721//Home/GetProductCats?id='+ x,
method:'GET',
success:function(d1){
this.setState({data2:d1});
}.bind(this),
error:function(){
alert('ERROR');
}.bind(this)
})
},
getData:function(){
//ajax here
$.ajax({
url:'http://localhost:53721//Home/GetProductCats',
method:'GET',
success:function(d1){
this.setState({data1:d1});
}.bind(this),
error:function(){
alert('ERROR');
}.bind(this)
})
}
});
var PRODOPTIONS = React.createClass({
render:function(){
return(<option value={this.props.optValue}>{this.props.optText}</option> )
}
});
var PRODCATSOPTION = React.createClass({
render:function(){
return(<option value={this.props.optValue}>{this.props.optText}</option> )
}
});
ReactDOM.render( <HCOMP/>, document.getElementById('d1') );
Try updating ddlProdCatsChanegeEvent to ddlPropCatsChangeEvent.
This is the code to a simple ToDo app using ASP.NET MVC:
var Appointment = Backbone.Model.extend({
defaults: function () {
return {
'date': new Date(),
'cancelled': false,
'title': 'Checkup'
}
}
});
var AppointmentList = Backbone.Collection.extend({
model: Appointment,
url:"/Home/Appointments"
});
var AppointmentView = Backbone.View.extend({
template: _.template('<span class="<% if(cancelled) print("cancelled") %>"><%= title %></span>x'),
initialize: function () {
this.model.on('change', this.render, this);
},
render: function () {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
var AppointmentListView = Backbone.View.extend({
initialize: function () {
this.collection.on('add', this.addOne, this);
this.collection.on('reset', this.render, this);
},
render: function () {
this.collection.forEach(this.addOne, this);
},
addOne: function (model) {
var appointmentView = new AppointmentView({ model: model });
appointmentView.render();
this.$el.append(appointmentView.el);
}
});
var AppRouter = new (Backbone.Router.extend({
routes: { "Home/Appointment/:id": "show", "": "index" },
initialize: function (options) {
this.appointmentList = new AppointmentList();
},
start: function () {
Backbone.history.start({ pushState: true });
},
index: function () {
var appointmentsView = new AppointmentListView({ collection: this.appointmentList });
appointmentsView.render();
$('body').html(appointmentsView.el);
this.appointmentList.fetch();
},
show: function (id) {
debugger;
var appointment = new Appointment({ id: id });
var appointmentView = new AppointmentView({ model: appointment });
appointmentView.render();
$('body').html(appointmentView.el);
appointment.fetch();
}
}));
$(function () { AppRouter.start() });
Please do not be overwhelmed by the code. If you look closely it is very simple as I am a noob.
My problem is that show action is not being hit. But index can works and can populate the page with view. I tried with all kinds of url to hit the show function but unsuccessful. Can someone please tell me what I need to do to make this right?
I'm trying to get a custom slider up and running using the directives concept.
I have an issue when updating the slider from the input field.
The directive part below and a working example on jsfiddle.
Why is this line $privateScope.sliderElement.slider('value', value); throwing an error and how could I solve it?
app.directive('slider', function ($parse) {
var $privateScope = {};
return {
restrict: 'A',
template: '<div class="slider"></div><div class="input-append"><input class="span1" type="text" ng-model="percentage"><span class="add-on">%</span></div>',
scope: {
slider: '#',
percentage: '='
},
controller: ['$scope', '$element', '$attrs', '$transclude', function ($scope, $element, $attrs, $transclude) {
// Why this doesn't work?
// $attrs.$observe('percentage', function (value) {
// console.log('$attrs.$observe.percentage', value);
// });
// Slider API: http://api.jqueryui.com/slider/
$privateScope.sliderElement = $('.slider', $element).slider({
value: $scope.percentage
});
}],
link: function ($scope, $element, $attrs) {
var changedBySlider = false;
$scope.$watch('percentage', function (value) {
// console.log('$scope.$watch.percentage', value);
if (changedBySlider !== true) {
console.log('change the slider');
// This throws an error
// $privateScope.sliderElement.slider('value', value);
} else {
console.log('don\'t change the slider');
changedBySlider = false;
}
});
$privateScope.sliderElement.on('slidechange', function (event, ui) {
$scope.$apply(function () {
// Why this doesn't work?
// $parse($attrs.percentage).assign($scope, ui.value);
$scope.percentage = ui.value;
changedBySlider = true;
});
});
$scope.$on('$destroy', function (event) {
console.log('on destroy');
});
}
}
});
I'm trying to add an addition tag to the end of the autocomplete list.
$('#address ul.ui-autocomplete').append("<li>Add Venue</li>");
I'm trying to figure out where I can place the code above to add the extra li to the autocomplete list.
Any help will be deeply appreciated.
This is the rails3-jquery-autocomplete file.
source: function( request, response ) {
$.getJSON( $(e).attr('data-autocomplete'), {
term: extractLast( request.term )
}, function() {
$(arguments[0]).each(function(i, el) {
var obj = {};
obj[el.id] = el;
$(e).data(obj);
});
response.apply(null, arguments);
});
},
open: function() {
// when appending the result list to another element, we need to cancel the "position: relative;" css.
if (append_to){
$(append_to + ' ul.ui-autocomplete').css('position', 'static');
}
},
search: function() {
// custom minLength
var minLength = $(e).attr('min_length') || 2;
var term = extractLast( this.value );
if ( term.length < minLength ) {
return false;
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
if (e.delimiter != null) {
terms.push( "" );
this.value = terms.join( e.delimiter );
} else {
this.value = terms.join("");
if ($(this).attr('data-id-element')) {
$($(this).attr('data-id-element')).val(ui.item.id);
}
if ($(this).attr('data-update-elements')) {
var data = $(this).data(ui.item.id.toString());
var update_elements = $.parseJSON($(this).attr("data-update-elements"));
for (var key in update_elements) {
$(update_elements[key]).val(data[key]);
}
}
}
var remember_string = this.value;
$(this).bind('keyup.clearId', function(){
if($(this).val().trim() != remember_string.trim()){
$($(this).attr('data-id-element')).val("");
$(this).unbind('keyup.clearId');
}
});
$(this).trigger('railsAutocomplete.select');
return false;
}
});
}
Solved it with this.
$('#address').bind('autocompleteopen', function(event,data){
$('<li id="ac-add-venue">Add venue</li>').appendTo('ul.ui-autocomplete');
});
I'm still finding my way with Backbone and I've always use Prototype instead of jQuery in the past so please forgive me if I'm doing something stupid.
I'm trying to develop a UI containing several connected unordered lists where each sortable list is represented by a separate Backbone collection. I'm using ICanHaz and Mustache templates but that's not of importance for my question.
When dragging items between the lists, how would I best achieve the automatic updating of the collections (remove a model from one and insert it into another)? I'm currently trying to use the receive and remove methods in the jQueryUI Sortable interaction — am I at least on the right lines?
var WS = {};
(function(ns) {
ns.Item = Backbone.Model.extend();
ns.Content = Backbone.Collection.extend({
model: ns.Item,
url: location.href,
initialize: function(el) {
this.el = $(el);
this.deferred = this.fetch();
},
recalculate: function() {
var count = this.length;
this.el.next(".subtotal").html(count);
},
setOrder: function() {
$.ajax({
url: this.url + "/reorder",
type: "POST",
data: "tasks=" + $(this.el).attr("id") + "&" + this.el.sortable("serialize")
});
}
});
ns.ContentRow = Backbone.View.extend({
tagName: "li",
className: "item",
events: {
"click .delete": "destroy"
},
initialize: function(options) {
_.bindAll(this, "render", "destroy");
this.model.bind("change", this.render);
this.model.view = this;
},
render: function() {
var row = ich.item(this.model.toJSON());
$(this.el).html(row);
return this;
},
destroy: function() {
if (confirm("Really delete?")) {
this.model.destroy({
success: function(model, response) {
$(model.view.el).remove();
},
error: function(model, response) {
console.log(response);
}
});
}
}
});
ns.ListView = Backbone.View.extend({
initialize: function(collection) {
this.el = collection.el;
this.collection = collection;
this.collection.bind("add", this.addOne, this);
_.bindAll(this, "addOne");
this.el.sortable({
axis: "y",
connectWith: ".tasks",
receive: _.bind(function(event, ui) {
// do something here?
}, this),
remove: _.bind(function(event, ui) {
// do something here?
}, this),
update: _.bind(function(event, ui) {
var list = ui.item.context.parentNode;
this.collection.setOrder();
}, this)
});
},
insert: function(item) {
var prefix = this.el.parentsUntil('ul').parent().attr("id"),
view = new ns.ContentRow({
model: item,
id: prefix + "_" + item.id
});
this.el.append(view.render().el);
},
addOne: function(item) {
if (item.isNew()) {
item.save({}, {
success: _.bind(function(model, response) {
// I should set id from JSON response when live
model.set({ id: this.collection.length });
this.insert(model);
}, this)
});
} else {
this.insert(item);
}
},
addAll: function() {
this.collection.each(this.addOne);
},
render: function() {
this.collection.deferred.done(_.bind(function() {
this.addAll();
}, this));
}
});
ns.AppView = Backbone.View.extend({
lists: [],
initialize: function(holder) {
holder.find("ul").each(_.bind(function(index, list) {
var Items = new WS.Content(list),
App = new WS.ListView(Items);
App.render();
this.lists.push(Items);
}, this));
}
});
})(WS);
$(document).ready(function() {
var App = new WS.AppView($("#tasks"));
});
You are on the right track. You will probably want to add the id of each sortable element into the template somewhere. Then when you receive the event, you know which model to add or remove from the collection. For example add...
<div data-id={{id}}> ... my thing ... </div>
And in the sortable call get the target's id attribute and call Collection.add() or remove()
Just use Backbone.CollectionView.. it has this functionality built in out of the box.
var listView = new Backbone.CollectionView( {
el : $( "#list1" ),
sortable : true,
sortableOptions : {
connectWith : "#list2"
},
collection : new Backbone.Collection
} );
var listView = new Backbone.CollectionView( {
el: $( "#list2" ),
sortable : true,
sortableOptions : {
connectWith : "#list1"
},
collection : new Backbone.Collection
} );