I am trying to create a view in Backbone and trying to load libs via node require. i am able to output to console from Model/Collection but when i start to create view i am getting error "Expecting a function in instanceof check, but got body". I tried to load View via $(function()({}) and also tried $('document').ready but no luck - any suggestions as to what i am missing or doing wrong here. Thank you
var express = require('express');
var $ = require('jQuery');
var _ = require('underscore');
var Backbone = require('Backbone');
var app = express();
app.use(express.static(__dirname + '/'));
app.listen(process.env.PORT || 3000);
var myModel = Backbone.Model.extend();
var myCollection = Backbone.Collection.extend({
model: myModel,
url: "myjson.json",
parse: function(response) {
return response.cars;
}
})
var cars = new myCollection();
var myView = Backbone.View.extend({
el: 'body',
initialize: function() {
cars.fetch();
this.render();
},
events: {
'click div.test': 'render'
},
render: function() {
cars.each(function(myModel) {
var _comp = myModel.get('make');
$('div.new_test').append(_comp);
console.log(_comp);
return this;
})
}
})
var yourView = new myView();
Maybe this might be a problem.
initialize: function() {
cars.fetch();
this.render();
},
You are fetching the collection ( Which is Asynchronous ) and immediately calling the render method.
Instead listen to the reset
event on the collection and which will fire after the collection is populated
initialize: function() {
this.listenTo(cars, 'reset', this.render);
cars.fetch();
},
And move the return this
to outside the $.each
loop.
Add Backbone.$ = $;
like so:
var express = require('express');
var $ = require('jQuery');
var _ = require('underscore');
var Backbone = require('Backbone');
Backbone.$ = $;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.