2015-10-17 99 views
0

如果使用dom-bind如何觀察屬性更改?屬性更改在大括號內更新,所以我假定有一些事件與更改有關,但我不知道它的名稱。如何使用dom-bind觀察屬性更改

例子:

<!doctype html> 
<html lang=""> 
<head > 
    <link rel="import" href="bower_components/polymer/polymer.html"> 
    <script src="bower_components/webcomponentsjs/webcomponents-lite.js"></script> 
    <style> 
    </style> 
</head> 

<body> 
<template is="dom-bind" id="app2"> 
    <p>test: <span>{{test}}</span></p> 
    <input type="button" value="Change" on-click="chTest"> 
</template> 
<script> 
    (function (document) { 
    'use strict'; 
    var app = document.querySelector('#app2'); 
    app.test = "original value"; 

    app.addEventListener('test-changed', function() { 
     console.log('change listener fired'); 
    }); 
    app.addEventListener('dom-change', function() { 
     console.log("dom-change"); 
    }); 
    app.chTest = function() { 
     console.log('click'); 
     app.test = "new value"; 
// notifyPath-setter will fire "test-changed"-event 
//  app.notifyPath("test", "notify value"); 
    }; 
    })(document); 
</script> 
</body> 
</html> 

編輯: 有必要澄清我的問題:我想調用一些功能,當app.test變化。

回答

0

您已將答案註釋掉。註釋行app.test,並取消對app.notifyPath

//  app.test = "new value"; 
// notifyPath-setter will fire "test-changed"-event 
     app.notifyPath("test", "notify value"); 

以下工作jsbin:

http://jsbin.com/vaqosi/edit?html,console,output

編輯:一種解決方法是雙向綁定成一個子元素,並聽取其變化。我已經更新了jsbin。

+0

對不起,我沒有足夠的解釋我的例子。 NotifyPath在代碼中僅用於測試事件偵聽器即。如果使用notifyPath,則測試更改的偵聽器將作出響應。我的問題是如何聆聽app.test-property中的更改。當app.test發生變化時,我想調用一些函數。 – grohjy

+0

明白了。一種解決方法是通過兩種方式將值綁定到子元素並監聽其更改。我已經更新了jsbin。 – Srik

+0

這似乎是目前最簡單的解決方案。基本上你需要添加一個簡單的自定義元素(例如:)到一個dom綁定模板中。觀察到的屬性綁定到自定義元素,並且每次更改屬性時都會觸發更改函數。 – grohjy