I'm new to meteor and I'm trying to get a hang of the whole reactivity thing.
There isn't a specifc reason why I want this function to re-run, in fact, it not re-running is actually the desired behavior for my use case. I just want to know why this is happening so I can better understand the concepts.
If I add a function as a property on a template instance, like this:
Template.services.onCreated( function() {
this.templates = [
"web_design",
"painting",
"gardening"
];
this.current_index = new ReactiveVar(0);
this.determineSlideDirection = function() {
console.log(this.current_index.get());
};
});
And then I update the reactive var in response to some event.
Template.services.events({
'click .nav-slider .slider-item': function(event, template) {
var new_selection = event.currentTarget;
template.current_index.set($(new_selection).index());
}
});
The function is not re-run upon the invocation of the set() call.
However, If I have a helper that utilizes the variable, it will be re-run.
Template.services.helpers({
currentTemplate: function() {
var self = Template.instance();
return self.templates[self.current_index.get()];
}
});
Why is this?
Reactive data sources only cause some functions to automatically re-run. These functions are:
Tracker.autorun
Template.myTemplate.helpers({})
Blaze.render and Blaze.renderWithData
In your code above you would want to use Tracker.autorun
Template.services.onCreated( function() {
this.templates = [
"web_design",
"painting",
"gardening"
];
this.current_index = new ReactiveVar(0);
Tracker.autorun(function(){
// actually, this might not work because the context of
// 'this' might be changed when inside of Tracker.
this.determineSlideDirection = function() {
console.log(this.current_index.get());
};
});
});
Related
I want to make use of the subscribe() function of knockout js to manually trigger an event at a certain point.
I could make an observable() and everytime put a GUID in there to trigger the scubscribe.
Is there a cleaner way within Knockout js to have a typical event-like structure?
Edit
Ok, apparently I can use observable.valueHasMutated() - might already a a bit cleaner that using a GUID.
Example
This is the behaviour that I'm looking for:
function Car()
{
var self = this;
self.onOpenDoor = ko.observable();
self.openDoor = function()
{
// using an observable / valueHasMutated for this feels a bit hacky
// is there an other way to use the underlying subscribe() system?
self.onOpenDoor.valueHasMutated();
}
}
var car = new Car();
// multiple subscribers
car.onOpenDoor.subscribe(function()
{
console.log('Do something');
})
car.o**nOpenDoor.subscribe(function()
{
console.log('Do something else');
})
car.openDoor();
I am aware this is not the default 'knockout' way to do stuff - that is not what this question is about.
Update
After #RoyJ's reference to Niemeyer's blog I went for this solution:
function Car()
{
var self = this;
self.onOpenDoor = new ko.subscribable();
self.openDoor = function()
{
self.onOpenDoor.notifySubscribers();
}
}
Update If you're just looking for clarity, you can use notifySubscribers instead of valueHasMutated. You might want to take a look at the base type of observables, ko.subscribable.
I would do it like this:
var vm = {
///...definitions...
openCount: ko.observable(0),
openDoor: function () {
vm.openCount(vm.openCount()+1);
}
};
vm.openCount.subscribe(function () {
///...do something
});
vm.openCount.subscribe(function () {
///...do something else
});
ko.applyBindings(vm);
Demo http://jsfiddle.net/uoqdfhdb/2/
For some reason I cannot comprehend, events are not being listened to by my View. The model IS changing, but the view doesn't seem to acknowledge these changes. Here's my code.
var playerSet = 1;
var bone = function(){
var app = {};
app.BoardModel = Backbone.Model.extend({
defaults: function(){
return{
board:[0,0,0,0,0,0,0,0,0],
allDisabled: false,
p1Score: 0,
p2Score: 0
}
},
setSlot: function(slot, ct){
var b = this.get("board");
b[slot] = ct;
this.set("board", b);
console.log("CHANGED");
}
});
app.Board = new app.BoardModel;
app.BoardView = Backbone.View.extend({
el: $("#ttt-board"),
initialize: function(){
this.listenTo(app.Board, "change", this.renderBoard);
},
renderBoard: function(){
console.log("HELLO THERE");
}
});
var tictac = new app.BoardView;
app.Board.setSlot(0,1);
};
bone();
When I fire setSlot, the model does change as the console outputs CHANGED, however I never see the renderBoard function being called.
This is probably incredibly simple, but it eludes me.
Your problem is that you are only changing the internal components of the array object, not the attribute on your model. Even though you are manually calling set on the model, this is not an actual change and the set logic only triggers a change event if the equality check between the old and new values fails (which in your case it doesn't).
Since you are calling a custom function anyways, why not just use a custom event?
setSlot: function(slot, ct){
this.get("board")[slot] = ct;
this.trigger("custom:change:board", slot, ct);
}
Now listen for the custom event (or both) instead of just change.
initialize: function(){
this.listenTo(app.Board, "change custom:change:board", this.renderBoard);
}
I guess that's the simple question. I'm new in js, especially in Backbone.js.
All I want to know is how I can refer to my function inside jquery function.
getLanguages: function() {
...
return languages;
},
render: function() {
...
$("input[type='checkbox']").bind("change", function() {
// todo: getLanguages
});
}
I tried to get languages via this but, of course, I got checkbox in this case.
Edit:
It's so simple. Many thanks to all!!!
This is a classic problem in Javascript. You need to reference this inside a callback, but this changes to the element being bound to. A cheap way to do it:
render: function() {
var that = this;
$("input[type='checkbox']").bind("change", function() {
that.getLanguages();
});
}
that will stay defined as the this that render is defined on.
However, you’re using Backbone, and it has more suitable ways to handle this situation. I don’t know the name of your Backbone.View class, but here’s an example adapted from the documentation:
var DocumentView = Backbone.View.extend({
events: {
"change input[type='checkbox']": "doSomething"
},
doSomething: function() {
this.getLanguages(); # uses the correct this
}
});
Calling bind inside render is not The Backbone Way. Backbone views are made to handle event delegation without the unfortunate need to pass this around.
Save this object before bind change event in the scope of render function.
render: function() {
var CurrentObj = this;
$("input[type='checkbox']").bind("change", function() {
CurrentObj.getLanguages();
});
}
You can save the appropriate object into a local variable so from the event handler, you can still get to it:
getLanguages: function() {
...
return languages;
},
render: function() {
...
var self = this;
$("input[type='checkbox']").bind("change", function() {
var lang = self.getLanguages();
...
});
}
I've learned that for scope reasons the this keyword inside an event listener, which is embedded in an object, doesn't refer to the global object but rather to the element which triggered the event.
Now, I understand that if I want to fetch a property I can save it to a variable before the event handler is called. But what can I do if I want to manipulate the property's value?
In the following piece of code I am trying to manipulate the drugCount property within the removeDrug event listener.
var Drugs = {
drugs: $("#drugs_table"),
drugRow: $("#drug").html(),
drugCount: 0,
init: function() {
this.addDrugRow();
this.removeDrugRowHandler();
},
addDrugRow: function() {
this.drugCount++;
this.drugs.append(this.drugRow.replace(/{{id}}/,this.drugCount));
$(".drugsSelect").select2();
},
removeDrugRowHandler: function() {
drugCount = this.drugCount;
// also a problematic solution, because it only retains the inital drugCount.
// i.e I need a way to access the "live" count from within the event
$(document).on("click",".removeDrug",function(){
if (drugCount>0) {
$(this).parents("tr").remove();
this.drugCount--; // how should I approach this?
}
});
}
}
Try This
var Drugs = function() {
var me = this;
me.drugs = $("#drugs_table");
me.drugRow = $("#drug").html();
me.drugCount = 0;
me.init = function() {
this.addDrugRow();
this.removeDrugRowHandler();
};
me.addDrugRow = function() {
this.drugCount++;
this.drugs.append(this.drugRow.replace(/{{id}}/,this.drugCount));
$(".drugsSelect").select2();
};
me.removeDrugRowHandler= function() {
var drugCount = me.drugCount;
$(document).on("click",".removeDrug",function(){
if (drugCount>0) {
$(this).parents("tr").remove();
me.drugCount--;
}
});
}
}
As it turns out the easy solution is to use the object name instead of the contextual this.
So instead of this.drugCount I used Drugs.drugCount.
However, this solution only works if I am in the context of a single object. If I were to write a "class" (i.e var Drugs = function(){ ... }) this won't work.
Is there a way to automatically do an _.bindAll for a backbone.js object?
I was talking to someone a while ago and they said that there was, but I have no idea where to start looking.
Example:
var TheView = Backbone.View.extend({
initialize: function() {
// HOW CAN I AVOID HAVING TO DO THIS?---->
_.bindAll(this,'render','on_element_01_click', 'on_element_02_click');
},
events: {
'click #element_01': 'on_element_01_click',
'click #element_02': 'on_element_02_click',
},
render: function(){
return this;
},
on_element_01_click: function(){
},
on_element_02_click: function(){
}
}
Do this instead:
_.bindAll(this);
Will bind ALL functions in this view.
I've since learned of a easier technique if you want to build bindAll in to your views (which is handy for things like AJAX callback methods that aren't auto-bound the way event handlers are). Basically you just override the constructor to perform the auto-binding.
var BoundModel = Backbone.Model.extend({
constructor: function() {
Backbone.Model.apply(this, arguments);
if (this.boundMethods) {
_(this).bindAll.apply(this, this.boundMethods);
}
}
})
var SubclassOfBoundModel = Backbone.Model.extend({
boundMethods: ['handleFetchResponse'],
initialize: function () {
this.model.on('sync', this.handleFetchResponse);
}
handleFetchResponse: function() {
// this function is bound to the model instance
}
})
Of course if you just wanted to bind all your methods you could leave out the "boundMethods" part and just have:
constructor: function() {
Backbone.Model.apply(this, arguments);
_(this).bindAll();
}
I tried doing this myself and I was able to get it working with something like this:
function bindOnExtend(clazz) {
var originalExtend = clazz.extend;
clazz.extend = function() {
var newSubClass = originalExtend.apply(this, arguments);
var originalInitialize = newSubClass.prototype.initialize;
newSubClass.prototype.initialize = function() {
// The constructor will get broken by bindAll; preserve it so _super keeps working
var realConstructor = this.constructor;
_.bindAll(this);
this.constructor = realConstructor;
originalInitialize.apply(this, arguments);
};
return bindOnExtend(newSubClass);
};
return clazz;
}
var BoundModel = Backbone.Model.extend();
bindOnExtend(BoundModel);
var BoundView = Backbone.View.extend();
bindOnExtend(BoundView);
However, I wouldn't recommend it. Doing that will make closures for every single method on every single model/view/whatever you instantiate. Not only does that add a slight increase in overall memory usage, it also opens up the possibility of memory leaks if you're not careful. Furthermore, it makes your stacktraces several lines longer, as they have to wind through bindOnExtend.
In my experience, having to do "_.bindAll(this, ..." is worth the trouble because:
1) it makes my code more clear/obvious to anyone coming after me
2) it encourages me to qualify my bindAll, instead of just using the 1-arg form
3) I hate wading through long stacktraces
But, if you want it the above code should work.