具有多种功能的骨干js模型解析函数

时间:2015-09-24 17:27:06

标签: javascript backbone.js marionette backbone-model

我对骨干很新,遇到了一个奇怪的问题

我的模型看起来像这样:

 define( function ( require, exports, module )
 {
     "use strict";

var Backbone = require( 'backbone' );

return Backbone.Model.extend(
    {

        defaults: {
            isLoggedin: false
        },

        url: 'http://api.com/login',

        parse: function( data ){
            //do stuff based on call

        },
        initialize: function(){


        },
        doLogin: function( data ){

            this.fetch({
                data: data,
                type: 'POST'
            });

            this.isUserLoggedIn();
        },

        isUserLoggedIn: function(){

            this.fetch({
                url:'http://api.com/loggedIn',
                type: 'GET'
            });
        }

       doLogout: function () {

            this.fetch({
                url:'http://api.com/logout',
                type: 'POST'

                });


         }

    });
} );

正如你所看到我发生了3个不同的功能我需要做的是基于我需要做不同动作或返回不同结果的函数但是有一个解析函数我怎么知道调用哪个函数做无论我在解析中需要什么。例如,如果调用isUserLoggedIn函数,我需要根据响应将它们重定向到某个页面,如果调用了doLogout,我需要根据响应将它们重定向到另一个页面。有任何想法吗?

2 个答案:

答案 0 :(得分:1)

你需要存储最后一个被调用的函数:

return Backbone.Model.extend(
{

    defaults: {
        isLoggedin: false
    },

    url: 'http://api.com/login',

    parse: function( data ){
        if(this.lastCall == 'doLogin'){
            //do staff if doLogin was called
            this.isUserLoggedIn();
        }
        if(this.lastCall == 'isUserLoggedIn'){
            //do staff if isUserLoggedIn was called
        }
        if(this.lastCall == 'doLogout'){
            //do staff if doLogout was called
        }

    },
    initialize: function(){


    },
    doLogin: function( data ){
        this.lastCall = 'doLogin';
        this.fetch({
            data: data,
            type: 'POST'
        });


    },

    isUserLoggedIn: function(){
        this.lastCall = 'isUserLoggedIn';
        this.fetch({
            url:'http://api.com/loggedIn',
            type: 'GET'
        });
    }

   doLogout: function () {
        this.lastCall = 'doLogout';
        this.fetch({
            url:'http://api.com/logout',
            type: 'POST'

            });


     }

});

答案 1 :(得分:0)

您可能希望使用包含选项的解析的第二个参数。

MY_CONST = {
  SOME_KIND_OF_URL: '/api/prod'
}

if (dev) {
  MY_CONST.SOME_KIND_OF_URL = '/api/foo';
}

MyModel = Bacbone.Model.extend({
  parse: function(response, options) {
    if (options.url === MY_CONST.SOME_KIND_OF_URL) {
  return 'foo';
    }
  }
},  MY_CONST)