backbone.js模型在成功后不会在fetch上更新

时间:2014-03-21 03:01:46

标签: javascript backbone.js underscore.js

我尝试在项目中使用backbone.js,但在尝试使用fetch方法更新模型时遇到问题。 我的模型如下(单身对象,因为我只想要一个实例)

 define([
'underscore',
'backbone'
], function (_, Backbone) {

var UserModel = Backbone.Model.extend({
    defaults: {
        name: "",
        loggedIn: false,
        user: "null",
        pass: "null"
    },

    prepare: function (options) {
        this.loggedIn = false;
        this.user = options.user;
        this.pass = options.pass;
    },

    url: function () {
        return _SERVER_ + "/WebServices/TTMobileAppService.svc/getUserLogin?user=" + this.user+"&pass="+this.pass;
    },

    parse: function (res) {
        // because of jsonp 
        return res.data;
    }

});

return new UserModel();

});

我的视图如下所示,当成功获取时,调用方法updateLogin,其中记录模型和响应。

定义([   ' jquery的&#39 ;,   '下划线&#39 ;,   '主链&#39 ;,   '模型/用户/的usermodel&#39 ;,   '!文本模板/登录/ loginTemplate.html' ],function($,_,Backbone,UserModel,loginTemplate){//},footerTemplate){

var LoginView = Backbone.View.extend({
    el: $("#loginArea"),
    events: {
        'mouseup #loginButton': 'expandLogin',
        'click #login': 'loginUser'
    },
    initialize: function () {
        this.options = { user: '', pass: "" };
        var that = this;
        this.model = UserModel;
        this.model.on('change', this.render, this);
        this.render();
    },
    render: function () {
        var data = {
            user: this.model.toJSON(),
            _: _
        };
        var compiledTemplate = _.template(loginTemplate, data);
        this.$el.html(compiledTemplate);
    },
    updateLogin: function(model, response, options) {
        console.log(model);
        console.log(response);
        console.log(options);
    },
    expandLogin: function () {
        var button = this.$el.children("div").first().children('#loginButton')[0];
        var box = this.$el.children("div").first().children('#loginBox')[0];
        $(box).fadeToggle(400);
        $(button).toggleClass('active');
    },
    loginUser: function () {
        var that = this;
        var username = $('#username_field', this.el).val();
        var password = $('#password_field', this.el).val();
        this.options = { user: username, pass: password };
        this.model.prepare(this.options);
        this.model.fetch({
            type: "GET",
            error: function (collection, response, options) {
                alert('error');
                alert(response.responseText);
            },
            success: that.updateLogin,
            complete: function () {
                alert('complete');
            },
            dataType: 'jsonp'
        });

    }

});

return LoginView;

});

目前我的模型尚未更新

model in firebug 但响应对象是正确和成功的 jsonp object returned fine

非常感谢任何帮助

1 个答案:

答案 0 :(得分:0)

 parse: function (res) {
    // because of jsonp 
    return res.data;
}

需要删除,它是从示例中复制的,尽管示例中的查询在对象内部有一个对象,与我的配置不同。现在已解决=]