4

vLineというjs APIでツールを作っているのですが、javascriptの基本的な質問なので投稿します。

サンプルコードにチャットシステムをつけたい。///chat関数の間に追加したもの

しかし

this.prototype.onMessage_ 

のようなエラーが表示されます

Uncaught TypeError: Cannot set property 'onMessage_' of undefined 

私はいくつかのJavaScriptプログラミングを作成しましたが、これは苦手です。だから私は理解していなかったと思う、非常に基本的なJavaScriptオブジェクト指向の何か。

私を助けてください。

<script>
var vlineClient = (function(){
  if('{{vlineData.serviceId}}' == 'YOUR_SERVICE_ID' || '{{vlineData.serviceId}}' == 'YOUR_SERVICE_ID'){
    alert('Please make sure you have created a vLine service and that you have properly set the $serviceID and $apiSecret variables in classes/Vline.php file.');     

    }


    var client, vlinesession,
          authToken = '{{ vlineData.authToken }}',
          serviceId = '{{ vlineData.serviceId }}',
          profile = {"displayName": '{{ vlineData.displayName }}', "id": '{{ vlineData.id }}'};

    // Create vLine client  
    window.vlineClient = this.client_ = vline.Client.create({"serviceId": serviceId, "ui": true});
    // Add login event handler

 this.client_.on('login', onLogin);
    this.client_.login(serviceId, profile, authToken).done(this.init_,this);
    // Do login

   **/////chat function**
     this.prototype.onMessage_ = function(event) {
        var msg = event.message,
        sender = msg.getSender();
         console.log('get message');
        this.showAlert(sender.getDisplayName(),
                     sender.getThumbnailUrl(),
                     msg.getBody());
    };
       this.client_.on('recv:im', this.onMessage_, this);
   **/////chat function**  









  function onLogin(event) {
    vlinesession = event.target;
    // Find and init call buttons and init them
    $(".callbutton").each(function(index, element) {
       initCallButton($(this)); 
    });
  }

  // add event handlers for call button
  function initCallButton(button) {
    var userId = button.attr('data-userid');

    // fetch person object associated with username
    vlinesession.getPerson(userId).done(function(person) {
      // update button state with presence
      function onPresenceChange() {
        if(person.getPresenceState() == 'online'){
            button.removeClass().addClass('active');
        }else{
            button.removeClass().addClass('disabled');
        }
        button.attr('data-presence', person.getPresenceState());
      }

      // set current presence
      onPresenceChange();

      // handle presence changes
      person.on('change:presenceState', onPresenceChange);



      // start a call when button is clicked
      button.click(function() {
              if (person.getId() == vlinesession.getLocalPersonId()) {
            alert('You cannot call yourself. Login as another user in an incognito window');
            return;
              }
          if(button.hasClass('active'))
                            **/////chat function**
                            person.postMessage("Hello there");
                            console.log("send message");
                             **////chat function**
            person.startMedia();
      });
    });

  }

  return client;
})();





$(window).unload(function() {
  vlineClient.logout();
});
4

1 に答える 1

1

あなたが書いた多くのことを理解することはできません。しかし、問題は非常に明確です。「これ」、あなたはあなたの方法であることを期待していますが、実行する場所に基づいてコンテキストが変わるため、これには非常に注意する必要があります。

コードを簡単に説明すると、次のようなモジュール パターンの例になります。

var moduleExample = (function () {
    // private variables and functions
    var privateVar = 'bar';

    // constructor
    var moduleExample = function () {
    };

    moduleExample.prototype.chat = function(){
        alert('hello');
    };

    // return module
    return moduleExample;
})();

var my_module = new moduleExample();
my_module.chat();

上記のコードで「this」の使用が回避されていることに注意してください。また、「new」を使用して新しいオブジェクトを作成する方法にも注意してください。

于 2013-06-26T08:53:50.080 に答える