I have what should be very simple. I create a new collection, and I want to pass it to a render and add the collection models to the page.
get_results: function(){
$.getJson(this.url,function(response){
this.search_results = new Kitchon.Collections.searchList(response);
console.log(this.search_results);
this.search_results.each(this.render_match);
}
},
render_match: function(model){
console.log(model)
},
This returns an error
Uncaught TypeError: undefined is not a function
my collection has an ordinary structure
_byCid: Object
_byId: Object
_onModelEvent: function () { [native code] }
_removeReference: function () { [native code] }
length: 7
models: Array[7]
__proto__: o
I’ve tried LOTS of things, but one thing that stuck out was maybe I had to pass
this.search_results.models.each(this.render_match); as that is the actual array, but if I do that I get a Uncaught typeError: Object [object Object],[object Object],...
you lose the execution context when callback function for each method is called
use
_.bind(this.render_match, this)when passing callback to make sure thatrender_matchhas the right contextand you were getting error because you didn’t wrap the callback function for
getJsonmethod neither. You have to use underscorebindmethod there as well.You should read a bit about javascript
thisand how to tame it – try here http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/Correct code should look more or less like this…
Though from what I seee – I assume the code you’ve shown here is either a model or collection – is handling rendering the view – you shouldn’t do that! Models and Collections are only to store and parse data – all rendering and controlling application flow should be done in the View(Controllers) with help of the Router.