0

In backbone I have created the following models,collections, and views

var sensor= Backbone.Model.extend({})

var sensorCollection = Backbone.Collection.extend({ model: sensor })

var sensors= new sensorCollection;

var SensorView =Backbone.View.extend({})

var AppView =Backbone.View.extend({})

var App = new AppView

I also have this PHP socket running:

var conn = new ab.Session('ws:localhost:8080', function() {
    conn.subscribe('temperature', function(topic, data) {
        console.log('Current temperature reading' + data.temperature);
        sensor.set({temperature:data.temperature});//Attempting to change backbone model

    });
}, function() {
    console.warn('WebSocket connection closed');
}, {
    'skipSubprotocolCheck' : true
}); 

I am attempting to change/update the model with the temperature reading coming in from socket. As you can see I have tried by sensor.set and also tried the following:

App.model.set

This.model.set

App.sensor.set

And each different way it either says undefined or something about the function not found. Am I missing something here? They are all declared in the same $(function(){}

How do I update my backbone model from my Autobahn socket function?

tereško
  • 58,060
  • 25
  • 98
  • 150
jacobronniegeorge
  • 557
  • 1
  • 10
  • 21

1 Answers1

0

Backbone.Model.extend({}) returns a class, not an instance. You should write instead:

var Sensor = Backbone.Model.extend({});
var sensor = new Sensor();

sensor.on('change:temperature', function (temperature) {
  console.log('new temperature: ' + temperature);
});

var conn = new ab.Session('ws:localhost:8080', function() {
    conn.subscribe('temperature', function(topic, data) {
        console.log('Current temperature reading' + data.temperature);
        sensor.set({temperature:data.temperature});//Attempting to change backbone model

    });
}, function() {
    console.warn('WebSocket connection closed');
}, {
    'skipSubprotocolCheck' : true
}); 
Laurent Perrin
  • 14,671
  • 5
  • 50
  • 49