Skip to content

kompolom/bem-mvc

 
 

Repository files navigation

BEM blocks library for MVC

bem-mvc library contains of i-bem blocks to enable you to realize MVC-pattern. Gives you an API to work with models and blocks for automated binding of models with the interface.

Due to active development of bem-core and bem-components libraries some functionalities may work incorrect! We work hard to stabilize it and welcome any efforts from you.

Models requirements:

  • Declarative style of models description;
  • Access to created samples of models by names and id;
  • Automated adjustment of fields values to given types;
  • Models validation.

Bindings requirements:

  • i-bem oriented;
  • Inheritance of own functionality in used i-bem blocks;
  • Bindings with controls from bem-components.

Dependancies:

Models

To use model it is necessary to declare it by seting up a name and fields description.

BEM.MODEL.decl('model', {
    name: 'string',
    birth: {
        type: 'string',
        preprocess: function(value) {
            return value.year + '.' + value.month + '.' + value.day;
        }
    },
    height: 'number',
    weight: 'number'
});

While declaring it is possible as well to set up model methods (redefinition of basic methods of a model will cause an error).

BEM.MODEL.decl('model', {
    name: 'string',
    hasBoyfriend: {
        type: 'boolean',
        default: false
    }
}, {
    toggleStatus: function() {
        this.set('hasBoyfriend', !this.get('hasBoyfriend'));

        return this;
    }
});

var model = BEM.MODEL.create('model', { name: 'Claudia Schiffer', hasBoyfriend: true });
model.toggleStatus();
model.get('hasBoyfriend'); // false

Types of fields:

  • string
  • number
  • boolean
  • model
  • array
  • models-list – a list of same type models

To create a model it is necessary to declare model name and to pass initialized parameters if needed.

var model = BEM.MODEL.create('model', {
    name: 'Claudia Schiffer',
    birth: {
        year: 1970,
        year: 1970,
        month: 8,
        day: 25
    },
    weight: 75,
    height: 180.5
});

In case of sample model link absence it is possible to call it from an internal storage by name.

var model = BEM.MODEL.get('model')[0];

Now we can set models fields:

model
    .set('weight', '80') // will be converted to number
    .set('height', 180)
    .update({
        weight: 80,
        height: 180
    });

And receive their values:

model.get('weight'); // 80
model.get('birth'); // '1970.8.25'

model.toJSON(); // all fields of a model

Events help us to find out about changes.

model.on('weight', 'change', function() {
    alert('Time to loose some weight!')