Skip to content
This repository has been archived by the owner on Jun 9, 2022. It is now read-only.

ValeriiVasin/backbone-mixin-state

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

23 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Backbone-mixin-state

Backbone mixin that helps you easily manage you view states.

Installation

NPM

npm install backbone-mixin-state --save

Bower

bower install backbone-mixin-state --save

State Model

  • Usual Backbone model
  • Provided value will always be converted to boolean
  • Contains convenience methods like .toggle()

Add view mixin

Add StateViewMixin mixin to you core view.

// lib/view.js
var StateViewMixin = require('backbone-mixin-state');
var View = Backbone.View.extend(StateView);

module.exports = View;

Example

var View = require('lib/view');
var StateModel = require('backbone-mixin-state/dist/model');

var MyView = View.extend({
  events: {
    'click .js-change-loading': 'changeLoadingState',
    'click .js-toggle-filled': 'toggleFilledState'
  },

  // required field that contains states definition
  states: {
    // root element states
    'loading': 'view-loading',
    'filled': 'view-filled',

    // child element state
    'filled .inner__block': 'is-filled'
  },

  statesDefaults: {
    loading: true,
    filled: false
  },

  initialize: function() {
    this.state = this.initStates(
      new StateModel(this.statesDefaults);
    );
  },

  changeLoadingState: function() {
    // => this.$el.removeClass('view-loading');
    this.state.set({ loading: false });
  },

  toggleFilledState: function() {
    // this.$el.addClass('view-filled');
    // this.$('.inner__block').addClass('is-filled');
    this.state.toggle('filled');
  }
});