如何使用骨干.js创建单独的模型、视图和控制器

how create separate model , view and controller using backbone.js

本文关键字:模型 视图 控制器 单独 何使用 js 创建      更新时间:2023-09-26
  • 再次编辑我的代码,我收到以下 2 错误:

1) 未定义Complex_collection

  model: Complex_model

2) 未定义Complex_model

 model: Complex_model

正在使用主干js,以下是我的代码,我通过使用骨干来完成此操作.js但我的代码没有运行我想要单独的模型,视图和使用主干js的控制器

//型

(function(){ var Complex_model = Backbone.Model.extend({        
    sync:function() {},
    validate:function() {},
    url:function() {},          
    defaults :{
        name : null
    }    
});})(this);

//视图

(function(){
FriendView = Backbone.View.extend({
    events :{
        'click #add-input' : 'add'
    },
    initialize: function(){
        this.collection = new Complex_collection(); // This is collection
        _.bindAll(this, 'render');
    },      
    add : function() {
        alert("hello");
        var friend_name = $('#input').val();
        this.collection.add({ name : friend_name });
    },
    render : function(){
        $("#friends-list").append("<li>"+ model.get("name")+"</li>");
    },      
});
var view = new FriendView(); })(this);

//收集

(function(){    
    var Complex_collection = Backbone.Collection.extend({
    model: Complex_model
});})(this);

谢谢

你不应该在初始化代码中创建同一对象的新实例,你的代码应该看起来像这样:

(function(){ 
    this.complex_model = Backbone.Model.extend({        
        sync:function() {},
        validate:function() {},
        url:function() {},      
    });
})(this);
// View
(function(){
    var vw = view = function(){};
    FriendView = Backbone.View.extend({
        events :{
            'click #add-input' : 'add'
        },
        initialize: function(){
            this.friendslist = new FriendList(); // This is your collection right?
            _.bindAll(this, 'render');
        },      
        add : function() {
            var friend_name = $('#input').val();
            this.friendslist.add({ name : friend_name });
        },
        render : function(){
            $("#friends-list").append("<li>"+ model.get("name")+"</li>");
        },      
    });
})(this);
// Collection
(function(){    this.complex_collection = Backbone.Collection.extend({
    model : complex_model
});})(this);
// Your main app
var view = new FriendView();