2012-04-21 38 views
6

Tôi cần sử dụng localStorage để lưu trữ một số đối tượng Ember. Tôi nhận thấy rằng các đối tượng Ember có các thuộc tính với các tên như __ember1334992182483. Khi tôi gọi JSON.stringify() trên các đối tượng Ember, các thuộc tính __ember* này không được đăng. Tại sao điều này? Tôi không nói rằng tôi muốn tuần tự hóa các thuộc tính đó. Tôi chỉ tò mò về chính xác chúng là gì và chúng được thực hiện như thế nào mà chúng không được sắp xếp theo thứ tự.Làm cách nào để nối tiếp các đối tượng Ember?

Tôi đang sử dụng cycle.js (https://github.com/douglascrockford/JSON-js/blob/master/cycle.js) để mã hóa cấu trúc dữ liệu có chứa tham chiếu trùng lặp thành chuỗi có thể được sử dụng để xây dựng lại cấu trúc dữ liệu gốc. Nó cho phép bạn làm điều này:

a = {a:1} 
b = {b:1} 
c = [[a, b], [b, a]] 

foo = JSON.stringify(JSON.decycle(c)) // "[[{'a':1},{'b':1}],[{'$ref':'$[0][1]'},{'$ref':'$[0][0]'}]]" 
JSON.retrocycle(JSON.parse(foo)) // reconstruct c 

Đối với đối tượng Ember tôi có thể làm điều tương tự, nhưng tôi cũng cần phải vượt qua các đối tượng deserialised vào Ember.Object.create() vì họ đang deserialised như đối tượng JavaScript đơn giản.

Đây có phải là cách tốt nhất để sắp xếp/deserialise các đối tượng Ember? Có một kỹ thuật được đề nghị cho việc này không?

Trả lời

0

Tôi sẽ sử dụng dữ liệu ember và viết bộ điều hợp dữ liệu cho việc này.

8

Đối serialization và deserialization bạn có thể làm một cái gì đó dọc theo các đường này, xem http://jsfiddle.net/pangratz666/NVpng/:

App.Serializable = Ember.Mixin.create({ 
    serialize: function() { 
     var propertyNames = this.get('propertyNames') || []; 
     return this.getProperties(propertyNames); 
    }, 

    deserialize: function(hash) { 
     this.setProperties(hash); 
    } 
}); 

App.Person = Ember.Object.extend(App.Serializable, { 
    propertyNames: 'firstName title fullName'.w(), 
    fullName: function() { 
     return '%@ %@'.fmt(this.get('title'), this.get('firstName')); 
    }.property('firstName', 'title') 
}); 

var hansi = App.Person.create({ 
    firstName: 'Hansi', 
    title: 'Mr.' 
}); 

// { firstName: 'hansi', title: 'Mr.', fullName: 'Mr. Hansi' } 
console.log(hansi.serialize()); 

var hubert = App.Person.create(); 
hubert.deserialize({ 
    firstName: 'Hubert', 
    title: 'Mr.' 
}); 
console.log(hubert.serialize());​ 

CẬP NHẬT: Cũng có một cái nhìn tại các câu hỏi tương tự Ember model to json

+0

Tại sao các '__ember * ' các thuộc tính không có trong đầu ra của 'JSON.stringify()'? – hekevintran

+0

Tôi phải đoán ở đây vì tôi không phải là chuyên gia về JavaScript: nhưng nếu bạn thực hiện 'for (prop in obj) {}' trên 'Ember.Object', không có' __ember * 'nào được liệt kê và kiểm tra' obj.hasOwnProperty' chỉ trả về true cho các thuộc tính được định nghĩa, xem http://jsfiddle.net/pangratz666/w53DH/. – pangratz

+0

Thuộc tính '__ember *' không được liệt kê trong vòng lặp 'for ... in'. Làm 'App.obj.hasOwnProperty ('__ ember1335029966963')' trả về 'true'. – hekevintran

0

tôi có:

  • fixe d và mã đơn giản
  • phòng ngừa thêm tham chiếu vòng tròn
  • thêm sử dụng get giá trị
  • loại bỏ tất cả các thuộc tính mặc định của một thành phần rỗng

    //Modified by Shimon Doodkin 
    //Based on answers of: @leo, @pangratz, @kevin-pauli, @Klaus 
    //http://stackoverflow.com/questions/8669340 
    
    App.Jsonable = Em.Mixin.create({ 
        getJson : function (keysToSkip, visited) { 
         //getJson() called with no arguments, 
         // they are to pass on values during recursion. 
    
         if (!keysToSkip) 
          keysToSkip = Object.keys(Ember.Component.create()); 
    
         if (!visited) 
          visited = []; 
    
         visited.push(this); 
    
         var getIsFunction; 
    
         var jsonValue = function (attr, key, obj) { 
          if (Em.isArray(attr)) 
           return attr.map(jsonValue); 
          if (App.Jsonable.detect(attr)) 
           return attr.getJson(keysToSkip, visited); 
          return getIsFunction?obj.get(key):attr; 
         }; 
    
         var base; 
         if (!Em.isNone(this.get('jsonProperties'))) 
          base = this.getProperties(this.get('jsonProperties')); 
         else 
          base = this; 
    
         getIsFunction=Em.typeOf(base.get) === 'function'; 
    
         var json = {}; 
    
         var hasProp = Object.prototype.hasOwnProperty; 
    
         for (var key in base) { 
    
          if (!hasProp.call(base, key) || keysToSkip.indexOf(key) != -1) 
           continue; 
    
          var value = base[key]; 
    
          // there are usual circular references 
          // on keys: ownerView, controller, context === base 
    
          if (value === base || 
           value === 'toString' || 
           Em.typeOf(value) === 'function') 
           continue; 
    
          // optional, works also without this, 
          // the rule above if value === base covers the usual case 
          if (visited.indexOf(value) != -1) 
           continue; 
    
          json[key] = jsonValue(value, key, base); 
    
         } 
    
         visited.pop(); 
         return json; 
        } 
    }); 
    
    /* 
    example: 
    
    DeliveryInfoInput = Ember.Object.extend(App.Jsonable,{ 
    jsonProperties: ["title","value","name"], //Optionally specify properties for json 
    title:"", 
    value:"", 
    input:false, 
    textarea:false, 
    size:22, 
    rows:"", 
    name:"", 
    hint:"" 
    }) 
    */ 
    
Các vấn đề liên quan