LeanCloud with Angularjs tips (1)

来源:互联网 发布:json打印出来 编辑:程序博客网 时间:2024/04/29 22:30

由于Angularjs使用的是plain object,而LeanCloud用的是一个封装起来的对象,所以没法简单的在angular里使用{{xx.yy}}这样的方式来绑定数据。

官方给出了方法是这篇Blog所述,使用Object.defineProperty来解决。

Object.defineProperty(Todo.prototype, "title", {      get: function() {        return this.get("text");      },      set: function(aValue) {        this.set("text", aValue);      }    });

这方法很好,所以我们可以直接写一个service来把它作为一个基础服务使用。

angular.module('demo')  .service('leancloud', function leancloud() {    var ClassDefines = {      'Product': {attributes: ['name', 'website']},      'ProductDetail': {attributes: ['size', 'price']}    };    return {      angularizeAll: function () {        angular.forEach(ClassDefines, function (classDefine, className) {          var classObject = AV.Object.extend(className);          angular.forEach(classDefine.attributes, function (attr) {            Object.defineProperty(classObject.prototype, attr, {              get: function () {                return this.get(attr);              },              set: function (value) {                this.set(attr, value);              }            });          })        })      }    }  });

在程序的开始执行

angular.module('demo').run(function (leancloud) {    leancloud.angularizeAll();  });

就可以尽情使用绑定带来的好处啦~

0 0