Ember.js Просмотр Binding не работает? - PullRequest
0 голосов
/ 20 февраля 2012

Я пытаюсь создать динамический отчет о продажах, который позволяет пользователям удалять строки клиентов из таблицы с помощью готового к использованию пользовательского интерфейса.Строка итогов, представляющая сумму всех проданных продуктов, должна быть обновлена ​​для удаления покупателя с дисплея.

Код (внизу сообщения) изначально показывает это:

product1:customer1 5
product2:customer1 6
product3:customer1 7
product1:customer2 5
product2:customer2 6
product3:customer2 7
product1:customer3 5
product2:customer3 6
product3:customer3 7
product1- 15
product2- 18
product3- 21

Затем я использую консоль для выполнения строки: Report.cellsController.toggleCustomerDisplay('customer2');

То, что я ОЖИДАЮ, это:

product1:customer1 5
product2:customer1 6
product3:customer1 7
product1:customer2 0
product2:customer2 0
product3:customer2 0
product1:customer3 5
product2:customer3 6
product3:customer3 7
product1- 10
product2- 12
product3- 14

Что я ПОЛУЧУ:

product1:customer1 5
product2:customer1 6
product3:customer1 7
product1:customer2 0
product2:customer2 0
product3:customer2 0
product1:customer3 5
product2:customer3 6
product3:customer3 7
product1- 15
product2- 18
product3- 21

Когда я запускаю функцию отладки Report.totalsController.spillguts (), мне сообщают, что ожидаемые значения там есть - так почему не обновляется мое представление?

Код:

<html>
  <head>
    <link rel="stylesheet" href="assets/bpm_styles.css" type="text/css" media="screen" charset="utf-8" />

    <title>my_app</title>


    <script type="text/x-handlebars" data-template-name='sales-report'>
        {{#each Report.cellsController}}
            <div>{{productID}}:{{customerID}} {{quantity}}</div>
        {{/each}}
        {{view Report.TotalProductsView}}
    </script>

    <script type="text/x-handlebars" data-template-name='total-products-report'>
        {{#each Report.totalsController}}
            <div>{{keyValue}}- {{quantity}}
        {{/each}}
    </script>

  </head>
  <body>
    <h1>Hello World</h1>
  </body>

  <script type="text/javascript" src="assets/bpm_libs.js"></script>
  <script type="text/javascript">
        spade.require('my_app');
        spade.require('ember');

        var Report = Em.Application.create();
        /**************************
        * Models
        **************************/
        Report.CustomerProductReportCellModel = Em.Object.extend({
            productID: '',
            customerID: '',
            originalQuantity: 0,
            display: true,

            quantity: function() {
                var display = this.get('display'),
                    originalQuantity = this.get('originalQuantity');

                return display ? originalQuantity : 0;
            }.property('display', 'originalQuantity')
        });

        Report.CustomerProductReportTotalCellModel = Em.Object.extend({
            primaryID: 'productID',
            keyValue: '',
            quantity: function(){
                var content = Report.cellsController.get('content');
                var currentDisplayQuantity = 0;
                var keyValue = this.get('keyValue');
                var primaryID = this.get('primaryID');

                content.forEach(function(cell){
                    if(cell[primaryID] == keyValue){
                        var qty = cell.get('quantity');
                        currentDisplayQuantity += qty;
                    }
                });

                return currentDisplayQuantity;
            }.property('Report.cellsController.content', 'keyValue', 'primaryID')
        });

        /**************************
        * Controller
        **************************/

        Report.cellsController = Em.ArrayController.create({
            content: [],
            createCellFromObjectLiteral: function(objLiteral) {

                var ourCell = Report.CustomerProductReportCellModel.create(objLiteral);
                this.pushObject(ourCell);
            },
            spillguts: function() { //for debugging purposes
                var content = this.get('content');
                content.forEach(function(cell){
                    //$('#debug').innerHTML += 
                    alert(cell.productID + ' ' + cell.customerID + ' ' + cell.originalQuantity + ':' + cell.get('quantity') + '<br />');
                });
            },

            toggleCustomerDisplay: function(customerID){
                var content = this.get('content');
                content.forEach(function(cell){
                    if(cell.get('customerID') == customerID){
                            var toggleToValue = !cell.get('display');
                            cell.set('display',toggleToValue);
                    }
                });
            }

        });

        Report.totalsController = Em.ArrayController.create({
            content: [],
            createTotalFromObjectLiteral: function(objLiteral) {
                var ourTotal = Report.CustomerProductReportTotalCellModel.create(objLiteral);
                this.pushObject(ourTotal);
            },
            spillguts: function() { //for debugging purposes
                var content = this.get('content');
                content.forEach(function(cell){
                    alert(cell.keyValue + ' ' + cell.get('quantity'));
                });
            }
        });

        //customer 1
        Report.cellsController.createCellFromObjectLiteral({productID: 'product1', customerID: 'customer1', originalQuantity: 5, display: true});
        Report.cellsController.createCellFromObjectLiteral({productID: 'product2', customerID: 'customer1', originalQuantity: 6, display: true});
        Report.cellsController.createCellFromObjectLiteral({productID: 'product3', customerID: 'customer1', originalQuantity: 7, display: true});

        //customer 2
        Report.cellsController.createCellFromObjectLiteral({productID: 'product1', customerID: 'customer2', originalQuantity: 5, display: true});
        Report.cellsController.createCellFromObjectLiteral({productID: 'product2', customerID: 'customer2', originalQuantity: 6, display: true});
        Report.cellsController.createCellFromObjectLiteral({productID: 'product3', customerID: 'customer2', originalQuantity: 7, display: true});

        //customer 3
        Report.cellsController.createCellFromObjectLiteral({productID: 'product1', customerID: 'customer3', originalQuantity: 5, display: true});
        Report.cellsController.createCellFromObjectLiteral({productID: 'product2', customerID: 'customer3', originalQuantity: 6, display: true});
        Report.cellsController.createCellFromObjectLiteral({productID: 'product3', customerID: 'customer3', originalQuantity: 7, display: true});

        //Product Totals
        Report.totalsController.createTotalFromObjectLiteral({primaryID: 'productID', keyValue: 'product1'});
        Report.totalsController.createTotalFromObjectLiteral({primaryID: 'productID', keyValue: 'product2'});
        Report.totalsController.createTotalFromObjectLiteral({primaryID: 'productID', keyValue: 'product3'});

        //alert(Report.totalsController.get('content')[1].get('quantity'));

        Report.MainView = Em.View.extend({
            templateName: 'sales-report'
        });

        Report.TotalProductsView = Em.View.extend({
            templateName: 'total-products-report'
        });

        //Report.mainView.append();

        var mainview = Report.MainView.create();
        mainview.append();

        //var totalproductsview = Report.TotalProductsView.create();
        //totalproductsview.append();
  </script>
</html>

Ответы [ 2 ]

3 голосов
/ 21 февраля 2012

Я понимаю, что вы пытаетесь сделать, но здесь есть некоторые нарушения.А именно, ваши модели не должны иметь жестко закодированных контроллеров.Это идет вразрез с шаблонами проектирования MVC.Другое - вы должны использовать .set() при создании ваших контроллеров.

Я переписал ваш код и поместил рабочее решение в this jsFiddle .Надеюсь, что это прояснит для вас.

0 голосов
/ 20 февраля 2012

Это должно быть обязательным для автообновления, не так ли?

...