我有一个系列,从这个系列我选择了一个模型。在这个模型中,我之前已经定义了一个函数。如何调用从集合中选择的模型函数?
我调用模型函数(但未定义):
var SingleHomePostView = Backbone.View.extend({
tagName: "li",
template: Handlebars.compile(template),
events: {
"click #retweet": "retweet",
},
initialize: function () {
// console.log(this.model);
this.model.bind("change", this.render, this);
this.model.bind("destroy", this.close, this);
},
render: function (eventName) {
var ad = this.model.toJSON();
ad.cid = this.model.cid;
$(this.el).html(this.template(ad));
return this;
},
retweet: function () {//Here----------
console.log(this.model);// is well defined
console.log("retweet");
console.log(this.model.reTweet()); //here I try to call model function
},
});
这是模型:
var Tweet = Backbone.Model.extend({
reTweet: function(){
var params = {
user_id: 11265832,
//screen_name:"brad"
page:1,
count:2,
};
cb.__call(
"statuses_userTimeline",
params,
function (reply) {
//gestire rate limit error 429
console.log(reply);
// return reply;
}
);
}
});
这是调用先前查看的主视图。它迭代集合并将模型传递给视图。
loadResults: function (eventName) {
//this.showSpinner();
console.log("homepostview"+this.page);
this.isLoading === true;
//console.log(this.IntegratedCollection);
_.each(this.IntegratedCollection.last(this.IntegratedCollection.length).reverse(), function(model){
$(this.el).append(new SingleHomePostView({
model: model
}).render().el);
},this);
this.isLoading === false;;
return this;
},
答案 0 :(得分:0)
好像你的集合应该指定Model类型。 See docs for more info
更新:
var Model = Backbone.Model = function(attributes, options) {
var attrs = attributes || {};
options || (options = {});
this.cid = _.uniqueId('c');
this.attributes = {};
if (options.collection) this.collection = options.collection;
if (options.parse) attrs = this.parse(attrs, options) || {};
attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
this.set(attrs, options);
this.changed = {};
this.initialize.apply(this, arguments);
};
要将模型与集合相关联 - 该集合不是由集合通过fetch创建的 - 只需在创建集合时将集合传递给模型(假设this.collection是您的实际集合实例):
new Model({collection: this.collection})