Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to add element from server ? #129

Closed
maxime-guyot opened this issue Mar 12, 2015 · 9 comments
Closed

How to add element from server ? #129

maxime-guyot opened this issue Mar 12, 2015 · 9 comments

Comments

@maxime-guyot
Copy link

Hi how to add element and emit to socket from server ?

var feathers = require('feathers');
var bodyParser = require('body-parser');
var app = feathers();

var todoService = {
    todos: [
        {
            text: 'Learn Feathers',
            complete: false
        }
    ],
    find: function (params, callback) {
        callback(null, this.todos);
    },
    create: function (data, params, callback) {
        this.todos.push(data);
        // Call back with the Todo data

        callback(null, data);
    }
}

// Configure REST and SocketIO endpointss
app.configure(feathers.rest());
app.configure(feathers.socketio());
// Parse JSON and form HTTP bodies
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));
// Use the Todo service object
app.use('/todos', todoService);
app.use(feathers.static(__dirname))
// Start the application on port 3030
app.listen(8080);


setInterval(function () {

    
    todoService.create({
        text: 'Hi!',
        complete: false
    },?????????);
   


}, 1000);


@daffl
Copy link
Member

daffl commented Mar 12, 2015

You have to use app.service like app.service('todos') to get the service. If you use todoService directly it won't have the additional Feathers functionality (like sending events to all the sockets). The timeout should look like this:

setInterval(function () {

  var service = app.service('todos');
  service.create({
      text: 'Hi!',
      complete: false
  }, {}, function(error, todo) {
    console.log('Created todo on server', todo);
  });;

}, 1000);

@maxime-guyot
Copy link
Author

Thank you for your answer,

But this does not emits message via the socket to the browser ...

I have to reload the page to see the new created by the server

@daffl
Copy link
Member

daffl commented Mar 12, 2015

How does your client look like? Are you listening to todos created?

@maxime-guyot
Copy link
Author

this is the client example on feathersjs.com :

<!DOCTYPE html>
<html>
    <head>
        <title>Feathers real-time Todos</title>
        <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
        <style type="text/css">
            .done {
                text-decoration: line-through;
            }
        </style>

        <div class="container" id="todos">
            <h1>Feathers real-time Todos</h1>

            <ul class="todos list-unstyled"></ul>
            <form role="form" class="create-todo">
                <div class="form-group">
                    <input type="text" class="form-control" name="description" placeholder="Add a new Todo">
                </div>
                <button type="submit" class="btn btn-info col-md-12">Add Todo</button>
            </form>
        </div>

        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script src="/socket.io/socket.io.js"></script>
        <script>
            var socket = io();
            var el = $('#todos');

            var app = {
                getElement: function (todo) {
                    return el.find('[data-id="' + todo.id + '"]')
                },
                addTodo: function (todo) {
                    var html = '<li class="page-header checkbox" data-id="' + todo.id + '">' +
                            '<label><input type="checkbox" name="done">' +
                            todo.text +
                            '</label><a href="javascript://" class="pull-right delete">' +
                            '<span class="glyphicon glyphicon-remove"></span>' +
                            '</a></li>';

                    el.find('.todos').append(html);
                    app.updateTodo(todo);
                },
                removeTodo: function (todo) {
                    app.getElement(todo).remove();
                },
                updateTodo: function (todo) {
                    var element = app.getElement(todo);
                    var checkbox = element.find('[name="done"]').removeAttr('disabled');

                    element.toggleClass('done', todo.complete);
                    checkbox.prop('checked', todo.complete);
                },
                errorHandler: function (error) {
                    if (error) {
                        alert(error.message);
                    }
                }
            };

            el.on('submit', 'form', function (ev) {
                var field = $(this).find('[name="description"]');

                socket.emit('todos::create', {
                    text: field.val(),
                    complete: false
                },
                {}, app.errorHandler);

                field.val('');
                ev.preventDefault();
            }).on('click', '.delete', function (ev) {
                var id = $(this).parents('li').data('id');
                socket.emit('todos::remove', id, {}, app.errorHandler);
                ev.preventDefault();
            }).on('click', '[name="done"]', function (ev) {
                var id = $(this).parents('li').data('id');

                $(this).attr('disabled', 'disabled');

                socket.emit('todos::update', id, {
                    complete: $(this).is(':checked')
                },
                {}, app.errorHandler);
            });

            socket.on('todos updated', app.updateTodo);
            socket.on('todos removed', app.removeTodo);
            socket.on('todos created', app.addTodo);
            socket.emit('todos::find', {}, function (error, todos) {
                todos.forEach(app.addTodo);
            });
        </script>
    </body>
</html>

@maxime-guyot
Copy link
Author

I tried on chrome and safari

@daffl
Copy link
Member

daffl commented Mar 12, 2015

I just tried by downloading the Gist for the example, extracting, in the folder running npm install feathers feathers-memory body-parser and added

setInterval(function () {

  var service = app.service('todos');
  service.create({
      text: 'Hi!',
      complete: false
  }, {}, function(error, todo) {
    console.log('Created todo on server', todo);
  });;

}, 1000);

At the bottom of app.js. Then I ran node app.js and went to http://localhost:8080 and I'm getting a new Todo every second in all browsers.

@maxime-guyot
Copy link
Author

So, i'm stupid !
this is my code :

setInterval(function () {
    var service = app.service('todos');
    todoService.create({ //!!!!
        text: 'Hi!',
        complete: false
    }, {}, function (error, todo) {
        console.log('Created todo on servcer', todo);
    }); 
}, 1000);

Thank you for your help ;)
nice work your framework !

@daffl
Copy link
Member

daffl commented Mar 12, 2015

Yeah sorry, I made that mistake first and edited it later so you probably got the wrong one via email. Thanks and glad I could help!

@lock
Copy link

lock bot commented Feb 8, 2019

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue with a link to this issue for related bugs.

@lock lock bot locked as resolved and limited conversation to collaborators Feb 8, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants