在Laravel 4中的.find jquery行中使用辅助函数

时间:2013-08-07 00:35:02

标签: jquery laravel laravel-4

我有一个帮助函数,我已将其设置为将时间戳转换为Laravel 4中的可读日期。该函数在文件StringEdit.php中称为“getDate”(在“helpers”文件夹中)。我知道这个功能有效。

我试图在jquery调用中使用此函数,该调用从数据库获取数据并将其加载到div id(每次单击时加载更多数据)。这是代码:

   <script type="text/javascript">
$(function() {

<?php $number_of_posts = 2; ?>;
<?php $_SESSION['posts_start'] = isset($_SESSION['posts_start']) ? $_SESSION['posts_start'] : $number_of_posts; ?>;
//<?php $_SESSION['posts_start'] = $_SESSION['posts_start'] ? $_SESSION['posts_start'] : $number_of_posts; ?>;
//<?php $_SESSION['posts_start'] = 2 ?>;

//var start = <?php echo $_SESSION['posts_start']; ?>;

var start = {{ Session::get('posts_start', 2) }};
var initialPosts = <?php echo Fanartist::friend_activity_json(0, $_SESSION['posts_start']); ?>;
//var initialPosts = <?php echo Fanartist::friend_activity_json(0, 2); ?>;
var desiredPosts = <?php echo $number_of_posts; ?>;


var template = '<tr>'
               +'<td>'
               +'<div class="friend_image">'
               +'<img src="https://graph.facebook.com/fbid/picture" alt="" height="65" width="65" class="img-rounded">'
               +'</div>'
               +'</td>'
               +'<td>'
               +'<div class="friend_activity">'
               +'<span class="activity_text"><span class="first_name"></span> <span class="last_name"></span> indicated that <span class="gender"></span> wants <a href="/artists/artist_id"><span class="stage_name"></span></a> to come to <span class="city"></span></span>'
               +'<br><span class="activity_subtext"><span class="created_at"></span></span>'
               +'</div>'
               +'</td>'
               +'</tr>';

var activity = $('#activity'),
    // Element to load the posts
    content = activity.find('.content'),
    // the more button
    more = activity.find('.more'),
    // the post counter
    counter = activity.find('.badge');

// Create alerts elements (Display Success or Failure)
    var alerts = {
        requestEmpty : $('<div class="alert alert-info">No more data</div>'),
        requestFailure : $('<div class="alert alert-error">Could not get the data. Try again!</div>')
    }
    var progressElement = $('<div class="progress" style="margin-bottom:0"><div class="bar"></div></div>');
    var progressBar = progressElement.find('.bar');

    var postHandler = function(posts){

        // Set the progress bar to 100%
        progressBar.css('width', '100%');
        // Delay the normal more button to come back for a better effect
        window.setTimeout(function(){more.html('More <span class="caret"></span>')}, 500);

        // insert childrens at the end of the content element


        for (post in posts){
            // Clone the element
            var $post = $(template).clone();
            $post.attr('id', 'post-' + posts[post].ID);

            var $img = $post.find('div.friend_image').find('img');
            $img.attr('src', $img.attr('src').replace('fbid', posts[post].fbid));
            $img.attr('alt', posts[post].first_name);

            var $spantext = $post.find('div.friend_activity').find('span.activity_text');
            $spantext.html($spantext.html().replace('artist_id', posts[post].artist_id));

            //$post.find('.fbid').html(posts[post].fbid);
            $post.find('.first_name').html(posts[post].first_name);
            $post.find('.last_name').html(posts[post].last_name);
            $post.find('.city').html(posts[post].city);
            $post.find('.gender').html(posts[post].gender == 'male' ? 'he' : 'she');
            //$post.find('.artist_id').html(posts[post].artist_id);
            $post.find('.stage_name').html(posts[post].stage_name);
            $post.find('.created_at').html(posts[post].created_at);
            content.append($post);

        }


        content.animate({
            scrollTop: $('#post-' + posts[0].ID).offset().top + (content.scrollTop()- content.offset().top)
        }, 200);

    }

    // place the initial posts in the page
    postHandler(initialPosts);

    // add the click event to the more button
    more.click(function(){  
        // Set the progress bar to 0%
        progressBar.css('width', '0%');
        // remove the more button innerHTML and insert the progress bar
        more.empty().append(progressElement);
        // AJAX REQUEST
        $.ajax({
            url: "http://crowdtest.dev:8888/fans/setup_widget", 
            type: 'GET',
            // We do not want IE to cache the result
            cache: false,
            data: {  
                'start': start,  
                'desiredPosts': desiredPosts  
            }
        }).success(function (data, text) {
            // parse the response (typeof data == String)
            data = JSON.parse(data);
            if (data.length > 0){
                // Update the total number of items
                start += data.length;
                // Update the counter
                counter.html(start);
                // load items on the page
                postHandler(data);
            }else{
                $alert = alerts.requestEmpty;
                // insert the empty message
                activity.prepend($alert);
                // Set the progress bar to 100%
                progressBar.css('width', '100%');
                // Remove the more button
                window.setTimeout(function(){more.remove()}, 500);
                // remove the empty message after 4 seconds
                window.setTimeout(function(){$alert.remove()}, 4000);
            }
        }).error(function (request, status, error) {
            $alert = alerts.requestFailure;
            // insert the failure message
            activity.prepend($alert);
            // Set the progress bar to 100%
            progressBar.css('width', '100%');
            // Delay the normal more button to come back for a better effect
            window.setTimeout(function(){more.html('More <span class="caret"></span>')}, 500);
        });

    });

console.log(desiredPosts);
console.log(start);
console.log(initialPosts);

});
</script>

使用div id“activity”在html中调用:

<div id="activity">
    <table class="table table-striped">
               <thead>
                   <tr>
                   <th><div class="friend_image"></div></th>
                   <th><div class="friend_activity"></div></th>
                   </tr>
               </thead>
               <tbody class="content">

               </tbody>
    </table>
<button class="more btn btn-block">
        More <span class="caret"></span>
</button>
</div>

除了created_at部分之外,所有内容都正确输出。我收到错误:

SyntaxError: missing ) after argument list

引用该行:

$post.find('.created_at').html(posts[post].StringEdit::getDate(created_at));

你知道如何调用这个函数在jquery中编辑数据库中的created_at实体吗?谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

为什么不在数据库的雄辩模型上使用Accessor,所以你根本不需要getDate()函数?

class User extends Eloquent {

    public function getCreatedAt($value)
    {
        // created_at will now be formatted as "d-m-Y"
        return date('d-m-Y', strtotime($value));
    }

}

只需将date()函数格式更改为您需要的格式(即与getDate()函数格式相同)

答案 1 :(得分:0)

根据你的回复,关于传递给刀片模板的变量,你写了你提出的javascript代码 - “它在刀片文件本身。而post变量是通过ajax绑定的。”

我想解决方案很简单 - 你可以完成你的需要只有刀片和php,没有JS(在你的情况下是多余的)

laravel控制器中的


1)将$ posts变量传递给视图(比返回它,显示或任何模板实现)

View::make('posts', $posts);
您的刀片模板中


1)将post变量提供给模板,就像你已经完成的那样 2)结构“模板”变量你在javascript中有一个刀片模板php代码
3)使用刀片用数据填充变量(而不是像现在这样用JS解析模板代码)

下面的一些示例(只是一个片段):

// app/views/posts.blade.php

{{-- this is a blade comment --}}

<div id="activity">
<table class="table table-striped">
           <thead>
               <tr>
               <th><div class="friend_image"></div></th>
               <th><div class="friend_activity"></div></th>
               </tr>
           </thead>
           <tbody class="content">

{{-- in the below foreach loop you put the html you currently have in javascript template variable var template; --}}

@foreach ($posts as $post)


{{-- inside the foreach loop you have access to all your $posts, so while iterating you can do:  --}}


{{-- 1) access $post fields --}}
{{ $post->id }} 
{{ $post->fbid }} 
{{ $post->whatever }} 

{{-- 2) access $post fields and apply function on them --}}
{{ StringEdit::getDate($post->whatever) }} 

@endforeach 

    </tbody>
</table>
<button class="more btn btn-block">
    More <span class="caret"></span>
</button>
</div>

如果您按照建议执行操作,则不必错误地将Php发送到Javascript问题,这对您的问题来说似乎更简洁,更简单。当然,你会得到你所要求的 - 你将能够在模板中使用字符串辅助函数:)

编辑:
我更新了上述帖子,以便在评论中包含讨论信息

编辑2:
从评论中回答您的跟进请求:

使用自定义Eloquent模型访问器

假设您的模型中有一个字段(datacolumn)(该字段代表数据库中的表),该字段的名称为MyFancyField。现在,对于您的系统,您需要有可能获取预处理此字段的内容 - 您需要它是大写的。因此,您创建一个类似下面的自定义访问器并引用它(使用它),就像它是模型的另一个字段一样。

型号:/app/models/Book.php

class Book extends Eloquent {

    protected $table = 'books';

    public function toArray()
{
    $array = parent::toArray();
    foreach ($this->getMutatedAttributes() as $key)
    {
        if ( ! array_key_exists($key, $array)) {
            $array[$key] = $this->{$key};   
        }
    }
    return $array;
}

public function getUpperMyFancyField()
{
    return strtoupper($this->myFancyField);    
}

}

控制器:/ app / controllers /

public function index(Book $book)
{
$this->book = $book;  

echo "The original field fetched by a default accessor: "  . $this->book->myFancyField;
echo "The uppercased field fetched by another custom accessor: "  . $this->book->upperMyFancyField;

}

仅仅为了记录,toArray()是故意重载的,因为Laravel 4默认情况下不会将“自定义访问器字段”包含在返回的对象中作为数组。所以,如果你没有这个,并且想要$ this-&gt; book-&gt; toArray(),那么就不会在那里包含upperMyFancyField。