복합 개체를 바인딩하는 방법(HTML)

[ 이 문서는 Windows 런타임 앱을 작성하는 Windows에서 8.x 및 Windows Phone 8.x 개발자를 대상으로 합니다. Windows 10용으로 개발하는 경우에는 최신 설명서를 참조하세요.]

대부분의 경우 앱에서 복합 개체, 특히 앱의 UI에서 제어할 수 없는 프로세스를 관리하는 개체에 바인딩하려고 합니다. 이 항목에서는 이름 및 색을 포함하는 개체에서 데이터를 표시하는 앱을 작성하는 방법에 대해 설명하며, 기본적으로 빠른 시작: 데이터 및 스타일 바인딩과 동일합니다. 이 경우 개체는 변경을 트리거하는 단추에 반응하는 대신 변경 프로세스 자체를 관리합니다.

사전 요구 사항

지침

단계 1: 바인딩을 사용할 프로젝트 설정

  1. JavaScript를 사용하여 빈 Windows 런타임 앱을 만들고 이름을 ObjectBinding으로 지정합니다.

  2. default.html에서 다음과 같이 바인딩용 DIV 요소를 추가하고, ID를 "objectBinding", 내부 텍스트를 Welcome으로 지정하고, SPAN 요소의 ID를 **"bindableSpan"**으로 지정합니다.

    <body>
        <div id="objectBinding">
          Welcome
          <span id="bindableSpan"></span>
        </div>
    </body>
    

단계 2: 복잡한 개체 설정

  1. 이름과 색 필드, 이름의 배열, 색 이름의 배열, 배열에 대해 임의 인덱스를 제공하기 위한 개인 메서드를 포함하는 Person 개체를 정의합니다. 이 개체의 정의를 위해 WinJS.Class.define 메서드를 사용할 수 있습니다. default.js에서 즉시 호출되는 익명 함수 내부에 다음 코드를 추가합니다.

    
    (function () {
        "use strict";
    
        // Other app code ...
    
        var Person = WinJS.Class.define(
            function() {
                this.name = "Harry";
                this.color = "blue";
                this.timeout = null;
            }, {
    
            _nameArray:
                ["Sally", "Jack", "Hal", "Heather", "Fred", "Paula", "Rick", "Megan", "Ann", "Sam"],
            _colorArray:
                ["lime", "lavender", "yellow", "orange", "pink", "greenyellow", "white", "lightblue", "lightgreen", "lightyellow"],
    
            _newName: function () {
                this.name = this._nameArray[this._randomizeValue(this._nameArray.length)];
                this.color = this._colorArray[this._randomizeValue(this._colorArray.length)];
            },
            _randomizeValue: function (max) {
                return Math.floor(Math.random() * 1000) % max); 
            }
        });
    
    })();
    
  2. 이제 500밀리초마다 이름과 색 필드를 변경하는 프로세스를 시작 및 중지하는 두 개의 공용 메서드를 Person 정의(WinJS.Class.define에 전달되는 두 번째 인수)에 추가합니다. WinJS.Class.define의 전체 호출이 아래에 표시됩니다.

    
    (function () {
        "use strict";
    
        // Other app code ...
    
        var Person = WinJS.Class.define(
            function() {
                this.name = "Harry";
                this.color = "blue";
                this.timeout = null;
            }, {
    
            _nameArray:
                ["Sally", "Jack", "Hal", "Heather", "Fred", "Paula", "Rick", "Megan", "Ann", "Sam"],
            _colorArray:
                ["lime", "lavender", "yellow", "orange", "pink", "greenyellow", "white", "lightblue", "lightgreen", "lightyellow"],
    
            _newName: function () {
                this.name = this._nameArray[this._randomizeValue(this._nameArray.length)];
                this.color = this._colorArray[this._randomizeValue(this._colorArray.length)];
            },
            _randomizeValue: function (max) {
                return Math.floor(Math.random() * 1000) % max); 
            },
    
            // Starts the process that changes the name.
            start: function () {
                var that = this;
                if (this.timeout === null) {
                    this.timeout = setInterval(function () { that._newName(); }, 500);
                }
            }, 
    
            // Stops the process that changes the name.
            stop: function () {
                if (this.timeout !== null) {
                clearInterval(this.timeout);
                    this.timeout = null;
                }
            }
        });
    
    })();
    

단계 3: 개체를 HTML에 바인딩

  1. 지금은 Person 개체를 관찰할 수 없습니다. 즉, 개체가 변경될 때 알림이 제공되지 않습니다. Person 개체를 정확한 바인딩 기능과 결합하여 이 개체를 관찰 가능하게 만들 수 있습니다. WinJS.Class.mix 함수는 bind 메서드가 포함된 WinJS.Binding.mixin 개체의 기능과 바인딩용 개체의 속성을 만드는 WinJS.Binding.expandProperties 함수의 기능을 Person 개체에 추가합니다. Person 개체 정의 다음에 WinJS.Class.mix를 호출합니다. (Person 클래스를 다른 것과 혼합하려면 먼저 정의해야 합니다.)

    WinJS.Class.mix(Person,
        WinJS.Binding.mixin,
        WinJS.Binding.expandProperties({name: "", color: ""})
    ); 
    
  2. 또한 Person 생성자 내부에서 _initObservable을 호출하여 _backingData 속성을 설정해야 합니다. Person 생성자를 다음과 같이 변경합니다.

    
    ...
    function () {
        this._initObservable();
    
        this.name = "Harry";
        this.color = "blue";
        this.timeout = null;
        }
    ...
    
  3. Person 개체를 인스턴스화하면 이것을 두 속성에 바인딩할 수 있습니다. bind 메서드는 두 개의 매개 변수를 사용합니다. 바인딩할 필드 또는 속성의 이름과 바인딩 방법을 지정하는 함수가 그것입니다. 이 함수에는 새 값과 이전 값의 두 매개 변수가 있습니다. bind는 인스턴스 메서드이므로, 지금은 단지 Person을 인스턴스화하여 이름과 색 필드에서 bind를 호출할 것입니다. default.js에서 다음 코드를 app.onactivated 이벤트 처리기 내부에 추가합니다.

    
    app.onactivated = function (args) {
    
        // Other activation code ...
    
        var myPerson = new Person();
    
        myPerson.bind("name", onNameChange);
    
        myPerson.bind("color", onColorChange);
    
        function onNameChange (newValue) {
            var span = document.getElementById("bindableSpan");
            span.innerText = newValue;
        }
    
        function onColorChange (newValue) {
            var span = document.getElementById("bindableSpan");
            span.style.color = newValue;
        }
    }
    

    경고  HTML 요소의 ID에 데이터를 바인딩하려 하지 마세요.

     

  4. 변경 이벤트가 발생할 수 있도록 하려면 Person._newName 함수를 변경해야 합니다.

    _newName: function () {
        this["name"] = this._nameArray[this._randomizeValue()];
        this['color"] = this._colorArray[this._randomizeValue()];
        }
    
  5. Person.start 메서드를 호출하여 바인딩을 테스트할 수 있습니다.

    myPerson.start();
    

    앱을 빌드하여 실행하면 다음이 표시됩니다.

    Welcome, Harry

    이름과 이름의 색이 계속해서 변경됩니다.

관련 항목

빠른 시작: 데이터 및 스타일을 HTML 요소에 바인딩