簡體   English   中英

如何將值從Collection收集到backbone.js中的模型

[英]how to Pass value From Collection to model in backbone.js

我想傳遞並從視圖中獲取一個值來模擬集合的使用,我能夠將值傳遞給模型,當我使用集合時它不起作用。我不知道這里的問題在哪里就是我的代碼。

我的模特

var PostwallModel=Backbone.Model.extend({

    urlRoot: 'http://localhost:3400/post',
    idAttribute: '_id',
    defaults : {
        userId: '',
        userName: " ",
        postmsg : "unknown"
    },

    initialize: function() {
        console.log("<><><>post model initialize<><><><><>");
    },

    // Delete item (row) from
    clear: function() {
        this.destroy();
    }

});

我的收藏

var PostwallCollection = Backbone.Collection.extend({
    url: 'http://localhost:3400/post',
    model: PostwallModel
});

**here is my view**

var PostwallView = Backbone.View.extend({

    el: $("#page"),
    template: _.template(PostwallTemplate),

    events: {
        'click #postinwall'        : 'submitpost',
    },

    initialize: function() {
        console.log("_______postmodel");
        this.model = new PostwallModel();
        var obj= new PostwallModel();
        obj.set({userId:'123',userName:"str ji",postmsg:'the post is here'});
        console.log(obj.get('postmsg'));
        obj.toJSON();

        console.log(JSON.stringify(obj));

        // console.log(obj.get('userName'));

        var collection = new PostwallCollection();

        _.bindAll(this, 'submitpost');

        console.log(collection);
        collection.add(obj,{id:1});
        console.log("collection"+collection);
        console.log("collection fetch value "+JSON.stringify(collection.fetch()));
        this.render();
    },

    render: function() {
        alert(" render function");
    },

    submitpost: function(e) {
        //Save post model to server data
        e.preventDefault();
        var post_data = JSON.stringify( this.getFormData( this.$el.find('form') ) );
        //
        //this.model.save(post_data);
        this.model.set(post_data);
        this.collection.add(this.model);
        return false
    },

    //Auxiliar function
    //how to get data from textarea

});

這里我進入控制台----> [],集合獲取值[對象對象] ,問題在哪里以及如何保存和獲取值。

嘗試這個:

var self = this;
collection.fetch()({
    success: function (data) {
        console.log("collection fetch value "+data);
        self.render();
    }
});

您只想在獲取成功后執行渲染。 fetch方法以異步方式運行。 這意味着在fetch方法仍在執行其操作時,它之后的所有內容仍將嘗試執行。 通過將render方法放在成功回調中,確保在實際擁有該數據之前不會嘗試使用您的收集數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM