backbone.js model not updating on fetch after success
I'm trying to use backbone.js in a project and having trouble when trying to update a model with the fetch
method. my model is as follows (singleton object as I only ever want one instance)
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();
});
my view is as below, when a successful fetch occurs the method updateLogin
is called where the model and response are logged.
define([ 'jquery', 'underscore', 'backbone', 'models/user/UserModel', 'text!templates/login/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;
});
currently my model isn't updated
but the response object is correct and successful
Any help would be greatly appreciated
parse: function (res) {
// because of jsonp
return res.data;
}
needed to be removed, it was copied from an example although the query in the example had an object inside an object unlike my configuration. resolved now =]
链接地址: http://www.djcxy.com/p/67082.html