深入分析Flex [Bindable] 以及使用方法[转]
??? 【IT168技术资讯】[Bindable]大概又是Flex用得最多的元数据了。刚开始用用确实好简单,效率真是没的说。不过这几天用着却碰到了些问题,我自己搜集了些资料,想着有必要在blog里总结一下吧。 ????啥是元数据(metadata) ????啥是绑定 [Bindable]? public var name:String = ""; ??? 作为一个public变量,肯定既可以被赋值,也能赋值给别的变量。绑定的作用就是,当name改变的时候(被赋值了),可能通知其它被name影 响(赋值给它们)的变量发生改变。这里的“可能”就需要编译器来判断,这就是为什么元数据是给编译器用的原因了。在mxml里用{}的语法的地方就是绑定 的对象,比如label={xxx.name},当name变化,label也跟着变化。这样,我们只是很简单的改变了name的值,由于有绑定,界面上 的label也跟着自动变化了,爽吧。 ????能用在哪里 ??? 用在只读,只写属性(getter/setter)上面 view plaincopy to clipboardprint? ? ? ??? 原来的设想是content绑定_wholeText,可它是不工作的。为什么?_wholeText太复杂了,被编译器排除在“可能”之外,编译器认为没有绑定关系,如果只是简单的return content,倒是可以的。我这里搜到了一些比较权威的解释。来自Ely Greenfield讲的。 Now keep in mind that there’s no way for the compiler to actually tell if the value of a property get function would be different if called,short of doing an extensive code flow analysis of the get function,identifying all the inputs that might be affecting the value of the get function (i.e.,member fields,statics,globals that are used in the get function and in any methods,global functions,closures,etc) it might call,and setting up watchers on every one of those to trigger the binding when any of them change. That’s prohibitively difficult,and expensive to do. So the compiler doesn’t try. Instead when you put [Bindable] on a get/set property,the compiler makes it bindable with a little creative rewriting that allows the framework to watch the get function,and dispatch a change event when the get function is triggered. This means that automatic bindable properties don’t work when the get function is computed from multiple values,or when you change its value by setting a backing field,rather than using the set function. It _also_ means that if you have no set function,we can pretty much guarantee that there’s no way automatically bindable get properties will be triggered. a read only propeerty is,to the compiler,completely opaque…at the moment,it has no idea where that value is coming from,and hence will never be able to ‘automatically’ trigger the binding. ??? 说白了就是为了降低复杂度和提高效率,复杂情况的getter会被忽略。如何解决?可以手动建立绑定,即[Bindable("eventName")]。把代码改成这样: view plaincopy to clipboardprint? ? ? ? ??? 这样就避免了编译器去自动识别。自己加上绑定关系,当_content被赋值,发出_contentChanged事件,通知所有被绑定的getter方法执行一遍。这也说明了,绑定不过是事件游戏而已,flex为用户隐藏了很多底层算法。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |