Skip to content

Dev.Front Js Backbone

nothing edited this page Aug 2, 2013 · 4 revisions

view

why

使用Backbone的主要目的是代码可维护性好,逻辑清晰,易于交互的改动。下面以一个表单验证功能为例子

Model

var UserModel = Backbone.Model.extend({
  urlRoot: '/users',
  idAttribute: 'username',
  validate: function(attrs, options) {
    var error = {};
    var msg;

    for (var i in attr) {
      msg = this.validateItem(i, attrs[i]);
        if (msg) {
          error[i] = msg;
        }
    }
    // If validate has return msg, it will trigger "invalid" event
    return !_.isEmpty(error) && error;
  },
  validateItem: function(key, val) {
    return this.validators[key] ? this.validators[key](val) : false;
  },
  initialize: function() {
    var self = this;
    //validators
    this.validators = {
      username: function(val) {
         if (!val) {
           return 'Please enter your username';
         } else if () {
         } else {
         // Check attribute uniqueness
           $.get('/users/check', {
             username: val
           }).done(function(res) {
             if (!res.status) {
               self.trigger('invalid', self, { username: 'Your username is already exist' });
             }
           });
         }
      },
      email: function(val) {
      },
      ...
    }
  }
});

View

交互以及业务逻辑代码主要在View层

var SignupView = Backbone.View.extend({
  className: 'modal-dialog modal-signup',
  events: {
    'click .js-create': 'create',
    'blur input': 'setVal',
    'submit form': 'create'
  },
  initialize: function () {
    this.model = new UserModel;
    this.model.on('invalid', this.inputFail, this); //validate fail
    this.model.on('change', this.inputSucc, this); //validate success
  },
  render: function () {
    this.inputTemplate = this.$('#input-msg-template').html();
    return this.el;
  },
  inputFail: function (model, error) {},
  inputSucc: function (model, current) {},
  setVal: function (e) {
    var tar = $(e.target);
    var name = tar.attr('name');
    var attr = {};

    attr[name] = $.trim(tar.val());
    this.model.set(attr, {
      validate: true
    });
  },
  create: function (e) {
    e.preventDefault();
    this.$('input').trigger('blur');
    if (!this.$('.text-danger').length) {
      this.model.save().done(_.bind(this.signupSuccess, this));
    }
  },
  signupSuccess: function (model, res) {}
});

template

<script type="text/template" id="signup-template">
 ...
</script>

form

Clone this wiki locally