Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor template updating

I am new to Meteor. I built simple test up and got stuck on very easy part. Content of my webpage updates only when db changes, but how can I force it update when function returning results changes? Here is part of code of my application:

client.js:

Meteor.subscribe("tasks");

var search_query = "";

Template.page.tasks = function() {
    return Tasks.find({title: {$regex: search_query}});
};

Template.task.events({
    'click .checkmark': function() {
        Tasks.update({_id: this._id}, {$set: {done: !this.done}});
    }
});

Template.page.events({
    'keyup .search': function() {
        search_query = $(".search").val();
    }
});

todo.html:

<head>
  <title>Todo list</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>
  {{> page}}
</body>

<template name="page">
    <div class="tasks">
        <h1>Collections TODOs</h1>
        <input type="text" class="search" placeholder="Search...">
        {{#each tasks}}
            {{> task}}
        {{/each}}
    </div>
</template>

<template name="task">
    <div class="task well well-small">
        <button type="button" class="close cancel">&times;</button>
        <h3>
            {{#if done}}
                <button type="button" class="checkmark done">&#10003;</button>
            {{else}}


    <button type="button" class="checkmark muted">&#10003;</button>
        {{/if}}
        {{title}}
    </h3>
    <div class="creator muted">{{creator}}</div>
    <p>{{description}}</p>
</div>

So now, I expect whenever user types something in input.search box variable search_query is changed and now Template.page.tasks returns different results. But nothing really updates. You can look at app on http://slava.meteor.com

like image 945
imslavko Avatar asked Jan 10 '13 22:01

imslavko


1 Answers

You need a reactive variable to dynamically run the search again. Make search_query a Session variable like this

Template.page.tasks = function() {
    return Tasks.find({title: {$regex: Session.get("search_query") }});
};

And in your event:

Template.page.events({
   'keyup .search': function() {
        Session.set("search_query", $(".search").val());
    }
});
like image 56
TimDog Avatar answered Nov 02 '22 01:11

TimDog